package com.snail.billing.session;

import java.util.Map;
import java.util.UUID;

import android.text.TextUtils;

import com.android.net.OnHttpHeaderListener;
import com.android.net.ResponseHandlerBitmap;
import com.snail.billing.DataCache;
import com.snail.billing.net.BillingHttpSession;
import com.snail.billing.net.BillingSecurity;

public class CaptchaSession extends BillingHttpSession implements OnHttpHeaderListener {

	private String uuid;
	private String isUseCaptcha;
	private static String HEADER_KEY;
	private static final String HEADER_VALUE = "1";

	public CaptchaSession(int hostType) {
		DataCache cache = DataCache.getInstance();
		String host = cache.importParams.hostImprest;
		if (hostType == 1) {
			host = cache.importParams.hostCard;
		}
		String formatUrl = null;
		BillingSecurity security = getSecurity();
		if (cache.importParams.isAccess) {
			formatUrl = "http://%s/Captcha.jpg?accountid=%s&asid=" + security.accessId + "&asty=" + security.accessType;
			HEADER_KEY = "show_" + security.accessId + "_" + security.accessType;
		} else {
			formatUrl = "http://%s/Captcha.jpg?accountid=%s";
			HEADER_KEY = "show_" + security.accessId + "_" + security.accessType;
		}
		uuid = UUID.randomUUID().toString();
		String address = String.format(formatUrl, host, uuid);
		setAddress(address);
		setResponseHandler(new ResponseHandlerBitmap());
		setOnHttpHeaderListener(this);
	}

	public boolean isUseCaptcha() {
		if (!TextUtils.isEmpty(isUseCaptcha) && HEADER_VALUE.equals(isUseCaptcha)) {
			return false;
		}
		return true;
	}

	public String getUuid() {
		return uuid;
	}

	@Override
	public Map<String, String> onHttpHeaderRequest() {
		return null;
	}

	@Override
	public void onHttpHeaderResponse(Map<String, String> headersMap) {
		for (String key : headersMap.keySet()) {
			if (key.equals(HEADER_KEY)) {
				isUseCaptcha = headersMap.get(key);
			}
		}
	}

	@Override
	public BillingSecurity getSecurity() {
		if (DataCache.getInstance().isSandbox) {
			return BillingSecurity.securitySandbox;
		}
		return BillingSecurity.security;
	}

}
